package com.hua.server.oauth.config.server;

import com.hua.server.oauth.strategy.TypeAuthorizationServerHandlerContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;

/**
 * oauth server config
 * clients config
 *
 * @author 华云龙
 * @date 2019-5-25
 */
@Configuration
@EnableAuthorizationServer
@Slf4j
public class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {

    private final PasswordEncoder passwordEncoder;

    @Value("${hyl.oauth.strategy:memory}")
    private String oauthStrategy;

    private final TypeAuthorizationServerHandlerContext typeAuthorizationServerHandlerContext;

    /**
     * 用户密码模式需要AuthenticationManager 支持
     * 授权码模式 不用
     */
    private final AuthenticationManager authenticationManager;

    public AuthorizationServerConfiguration(PasswordEncoder passwordEncoder, AuthenticationManager authenticationManager, @SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection") TypeAuthorizationServerHandlerContext typeAuthorizationServerHandlerContext) {
        this.passwordEncoder = passwordEncoder;
        this.authenticationManager = authenticationManager;
        this.typeAuthorizationServerHandlerContext = typeAuthorizationServerHandlerContext;
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints
                .authenticationManager(authenticationManager)
                .tokenStore(typeAuthorizationServerHandlerContext.getInstance(oauthStrategy).configure(endpoints));
    }

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        log.debug("clients config type:{}", oauthStrategy);
        typeAuthorizationServerHandlerContext.getInstance(oauthStrategy).configure(clients, passwordEncoder);
    }

}
